<?php
include_once "../../inc/common.inc.php";
require_once ROOT_PATH."inc/weixin/WxPay.Exception.php";
require_once ROOT_PATH."inc/weixin/WxPay.Data.php";
require_once ROOT_PATH."inc/weixin/WxPay.Api.php";
require_once ROOT_PATH."inc/weixin/WxPay.Notify.php";

//初始化日志
class PayNotifyCallBack extends WxPayNotify
{
	public $pay_config;
	//查询订单
	public function Queryorder($transaction_id)
	{
		global $base;
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		WxPayApi::$config=$this->pay_config;
		$result = WxPayApi::orderQuery($input);
		//$result=array ( 'appid' => 'wx7633dd15d4626193', 'attach' => 'F-time儿童手表女孩', 'bank_type' => 'CFT', 'cash_fee' => '1', 'fee_type' => 'CNY', 'is_subscribe' => 'Y', 'mch_id' => '1483069522', 'nonce_str' => 'flipboqrnsy3ff33fswzw1utefkt6v49', 'openid' => 'o0npWwOJaQROV7_E6jr0rjgg4oFM', 'out_trade_no' => 'dcd3c84c364e01a15478', 'result_code' => 'SUCCESS', 'return_code' => 'SUCCESS', 'sign' => 'BDB3F6EB1E85CEE3D3F690D43DE5B950', 'time_end' => '20180525110350', 'total_fee' => '1', 'trade_type' => 'JSAPI', 'transaction_id' => '4200000111201805253863441293');
		
		if(array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS")
		{
			if(!empty($result['out_trade_no']))
			{
				$total_fee=round(floatval($result['total_fee']/100),2);
				$list = $base->bidcms_model('order_base',ROOT_PATH.'store/models/')->get_page(array('and order_parent_sn=:sn',array(':sn'=>$result['out_trade_no'])));
				foreach($list as $info){
					if($info['id']>0 && $info['pay_status']==0)
					{
						$order_status=1;
						if($info['activity_type']=='offline'){
							$order_status=3;
						}
						//修改订单支付状态，支付金额，支付时间
						$base->bidcms_model('order_base',ROOT_PATH.'store/models/')->update_data(array('and id=:id',array(':id'=>$info['id'])),array('paid'=>$total_fee,'pay_status'=>1,'pay_appid'=>$result['appid'],'order_status'=>$order_status,'pay_time'=>time(),'pay_id'=>$result['transaction_id'],'pay_mchid'=>$result['mch_id']));
						
						$activity_type=explode(',',$info['activity_type']); //一个订单里可能包含多个活动的商品
						if(!empty($activity_type[0])){ //活动勾子
							$activity_id=explode(',',$info['activity_id']);
							foreach($activity_type as $k=>$v){
								$hook=$base->bidcms_hook($v);
								if($hook){
									$hook->order_pay_success($activity_id[$k],$info,$result);
								}
							}
						}
						$base->bidcms_model('order_commission',ROOT_PATH.'store/models/')->update_data(array('and order_id=:sn',array(':sn'=>$info['id'])),array('order_status'=>1));
						if($info['activity_type']!='offline'){
							//更新商品销量
							$goods_list=$base->bidcms_model('order_goods',ROOT_PATH.'store/models/')->get_page(array('and order_id=:oid',array(':oid'=>$info['id'])));
							foreach($goods_list as $key=>$goods){
								$base->bidcms_model('goods_base',ROOT_PATH.'store/models/')->exec_sql('update %s set sale_num=sale_num+'.intval($goods['num']).' where id='.$goods['goods_id']);
							}
							//更新用户购买次数和金额
							$base->bidcms_model('customer_count',ROOT_PATH.'wxapp/models/')->exec_sql('update %s set buy_count=buy_count+1,buy_amount=buy_amount+'.$total_fee.' where customer_id='.$info['customer_id']);
						}
					}
				}
			}
			return true;
		}
		return false;
	}
	//查询订单
	public function test()
	{
		global $base;
		$result=array ( 'appid' => 'wx7633dd15d4626193', 'attach' => 'F-time儿童手表女孩', 'bank_type' => 'CFT', 'cash_fee' => '1', 'fee_type' => 'CNY', 'is_subscribe' => 'Y', 'mch_id' => '1483069522', 'nonce_str' => 'flipboqrnsy3ff33fswzw1utefkt6v49', 'openid' => 'o0npWwOJaQROV7_E6jr0rjgg4oFM', 'out_trade_no' => '5037b7510ddfcc5c4576', 'result_code' => 'SUCCESS', 'return_code' => 'SUCCESS', 'sign' => 'BDB3F6EB1E85CEE3D3F690D43DE5B950', 'time_end' => '20180525110350', 'total_fee' => '1', 'trade_type' => 'JSAPI', 'transaction_id' => '4200000111201805253863441293');
		
		if(array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS")
		{
			if(!empty($result['out_trade_no']))
			{
				$total_fee=round(floatval($result['total_fee']/100),2);
				$list = $base->bidcms_model('order_base',ROOT_PATH.'store/models/')->get_page(array('and order_parent_sn=:sn',array(':sn'=>$result['out_trade_no'])));
				
				foreach($list as $info){
					if($info['id']>0)
					{
						$order_status=1;
						if($info['activity_type']=='offline'){
							$order_status=3;
						}
						//修改订单支付状态，支付金额，支付时间
						//$base->bidcms_model('order_base',ROOT_PATH.'store/models/')->update_data(array('and id=:id',array(':id'=>$info['id'])),array('paid'=>$total_fee,'pay_status'=>1,'pay_appid'=>$result['appid'],'order_status'=>$order_status,'pay_time'=>time(),'pay_id'=>$result['transaction_id'],'pay_mchid'=>$result['mch_id']));
						
						$activity_type=explode(',',$info['activity_type']); //一个订单里可能包含多个活动的商品
						
						if(!empty($activity_type[0])){ //活动勾子
							$activity_id=explode(',',$info['activity_id']);
							foreach($activity_type as $k=>$v){
								$hook=$base->bidcms_hook($v);
								if($hook){
									$hook->order_pay_success($activity_id[$k],$info,$result);
								}
							}
						}

						$base->bidcms_model('order_commission',ROOT_PATH.'store/models/')->update_data(array('and order_id=:sn',array(':sn'=>$info['id'])),array('order_status'=>1));
						if($info['activity_type']!='offline'){
							//更新商品销量
							$goods_list=$base->bidcms_model('order_goods',ROOT_PATH.'store/models/')->get_page(array('and order_id=:oid',array(':oid'=>$info['id'])));
							foreach($goods_list as $key=>$goods){
								$base->bidcms_model('goods_base',ROOT_PATH.'store/models/')->exec_sql('update %s set sale_num=sale_num+'.intval($goods['num']).' where id='.$goods['goods_id']);
							}
							//更新用户购买次数和金额
							$base->bidcms_model('customer_count',ROOT_PATH.'wxapp/models/')->exec_sql('update %s set buy_count=buy_count+1,buy_amount=buy_amount+'.$total_fee.' where customer_id='.$info['customer_id']);
						}
					}
				}
			}
			return true;
		}
		return false;
	}
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
		global $base;
		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//获取系统支付配置信息
		$config=$base->bidcms_model('shop_pay',ROOT_PATH.'wxapp/models/')->get_one(array('and app_id=:appid and tag=:tag',array(':appid'=>$data['appid'],':tag'=>'OWNED')));
		$pay_config=json_decode(htmlspecialchars_decode($config['value']),true);
		$pay_config['sslcert_path']=ROOT_PATH.'data/cert/'.$pay_config['ssl_cert'].'/apiclient_cert.pem';
		$pay_config['sslkey_path']=ROOT_PATH.'data/cert/'.$pay_config['ssl_cert'].'/apiclient_key.pem';
		$pay_config['curl_proxy_host']='0.0.0.0';
		$pay_config['curl_proxy_port']=0;
		$pay_config['report_level']=1;
		$this->pay_config=$pay_config;
		
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		return true;
	}
}
$notify = new PayNotifyCallBack();
$notify->Handle(true,$notify->pay_config);
